<template>
  <el-dialog
    :width="'80%'"
    :visible="dialogVisible"
    :title="`${name}统计`"
    append-to-body
    @close="$emit('close')"
  >
    <el-form>
      <el-form-item label="选择查询时间">
        <el-date-picker
          v-model="timeRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
          @change="fetchAll"
        />
      </el-form-item>

    </el-form>
    <div
      v-loading="loading"
    >
      <h3>{{ name }}使用率</h3>
      <div
        v-show="chartData.length"
       
        id="usageChart"
        style="{
          width: 100%;
          height: 400px;
        }"
      />
      <el-empty
        v-if="!chartData.length"
        description="暂无数据"
      />
    </div>
    <div
      v-if="name !== '存储'"
      v-loading="loading"
    >
      <h3>{{ name }}分配率</h3>
      <div
        v-show="desChartData.length"
        id="distributeChart"
        style="{
          width: 100%;
          height: 400px;
        }"
      />
      <el-empty
        v-if="!desChartData.length"
        description="暂无数据"
      />
    </div>
  </el-dialog>
</template>

<script>
import overviewApi from '@/api/monitor/overview'
import echarts from 'echarts'
import { timeAxisLabel } from '@/utils/chartOption'
import elementResizeDetectorMaker from 'element-resize-detector'
import dateUtil from '@/utils/date'

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    name: {
      type: String,
      default: ''
    },
    cmFlag: {
      type: String,
      default: ''
    },
    clusterFlag: {
      type: String,
      default: ''
    }
  },
  emits: ['close'],
  data() {
    return {
      data: [],
      desData: [],
      loading: false,
      chartData: [],
      desChartData: [],
      timeRange: []
    }
  },
  watch: {
    async dialogVisible(val) {
      if (val) {
        this.timeRange = [
          dateUtil.getDateStr(new Date(new Date().getTime() - 60 * 60 * 1000)),
          dateUtil.getDateStr(new Date())
        ]
        await this.fetchAll()
      }
    }
  },
  methods: {
    async fetchAll() {
      const promiseList = [
        this.getDataUsage()
      ]
      if (this.name !== '存储') {
        promiseList.push(this.getDataDistribution())
      }
      this.loading = true
      await Promise.all(promiseList)
      this.loading = false
    },
    statisticTooltip (params) {
      const htmlStr = `<div><p>${this.name}使用值:${this.data[params[0].dataIndex].value}</p><p>${this.name}使用率:${this.data[params[0].dataIndex].distribution}%</p></div>`
      return htmlStr
    },
    desStatisticTooltip (params) {
      const htmlStr = `<div><p>${this.name}分配值:${this.desData[params[0].dataIndex].value}</p><p>${this.name}分配率:${this.desData[params[0].dataIndex].distribution}%</p></div>`
      return htmlStr
    },
    async getDataUsage() {
      let data
      const params = {
        cmFlag: this.cmFlag,
        clusterFlag: this.clusterFlag,
        startTime: this.timeRange[0],
        endTime: this.timeRange[1]
      }
      switch (this.name) {
        case 'CPU':
          data = await overviewApi.cpuUsed(params)
          break
        case '内存':
          data = await overviewApi.memoryUsed(params)
          break
        case '存储':
          data = await overviewApi.hdfsUsed(params)
          break
      }
      if (data) {
        this.data = data
        this.chartData = []
        this.data.forEach((item, index) => {
          this.chartData[index] = [item.createTime, item.distribution]
        })
        this.initChart()
      }
    },
    async getDataDistribution() {
      let data
      const params = {
        cmFlag: this.cmFlag,
        clusterFlag: this.clusterFlag,
        startTime: this.timeRange[0],
        endTime: this.timeRange[1]
      }
      switch (this.name) {
        case 'CPU':
          data = await overviewApi.cpuDistribution(params)
          break
        case '内存':
          data = await overviewApi.memoryDistribution(params)
          break
        case '存储':
          data = await overviewApi.hdfsUsed(params)
          break
      }
      if (data) {
        this.desData = data
        this.desChartData = []
        this.desData.forEach((item, index) => {
          this.desChartData[index] = [item.createTime, item.distribution]
        })
        this.initChart2()
      }
    },
    initChart() {
      const chart = echarts.init(document.getElementById('usageChart'))
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: this.statisticTooltip
        },
        calculable: true,
        xAxis: {
          type: 'time',
          axisLabel: timeAxisLabel
        },
        yAxis: {
          type: 'value',
          axisLabel: {formatter: '{value}%'}

        },
        series: [
          {
            type: 'line',
            data: this.chartData
          }
        ]
      })
      const erd = elementResizeDetectorMaker()
      erd.listenTo(document.getElementById('usageChart'), (element) => {
        chart.resize()
      })
    },
    initChart2() {
      const chart = echarts.init(document.getElementById('distributeChart'))
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: this.desStatisticTooltip

        },
        calculable: true,
        xAxis: {
          type: 'time',
          axisLabel: timeAxisLabel
        },
        yAxis: {
          type: 'value',
          axisLabel: {formatter: '{value}%'}
        },
        series: [
          {
            type: 'line',
            data: this.desChartData
          }
        ]
      })
      const erd = elementResizeDetectorMaker()
      erd.listenTo(document.getElementById('distributeChart'), (element) => {
        chart.resize()
      })
    }
    
  }
}
</script>

<style lang="scss" scoped>

</style>
